<template>
  <d2-container>
    <el-card shadow="never" class="d2-mb">
      <el-form
        class="filter-container"
        ref="FYForm"
        :model="FYForm"
        label-width="85px"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="名称" prop="name">
              <el-input v-model="FYForm.name" placeholder="请输入名称" style="width:100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="币种">
               <el-select
                v-model="FYForm.id"
                placeholder="请选择"
                style="width:100%;"
              >
               <el-option
                         v-for="item in selectCurrencyList"
                         :key="item.currency"
                         :label="item.name"
                         :value="item.currency"
                 >
                     <span style="float: left">{{item.name}}</span>
                     <!-- <span style="float: right; color: #8492a6; font-size: 13px">{{ item.currency}}</span> -->
                 </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select  clearable v-model="FYForm.status" placeholder="请选择" filterable allow-create>
			           <el-option label="停用" value="0"></el-option>
                 <el-option label="启用" value="1"></el-option>
			        </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
          <el-button type="primary" size="small" @click="handlefee_typeChange" style='margin-top:3px;'>
            <d2-icon name="search" /> 查询
          </el-button>
        </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="mb">
      <el-button type="default" size="small" @click="add_fee_type">
        <d2-icon name="plus" />
        新增
      </el-button>
      <el-button type="default" size="small" @click="edit_fee_type">
        <d2-icon name="edit" />
        修改
      </el-button>
      <el-button type="default" size="small" icon="el-icon-delete" @click="del_fee_type">
        删除
      </el-button>
      <!-- <el-button type="default" size="small" @click="examine">
        <d2-icon name="search" />
        查看
      </el-button> -->
       <el-upload
            class="upload-btn"
            :action="uploadUrl"
            accept=".xls, .xlsx"
            :on-success="handleAvatarSuccess"
            :on-progress="uploadProgress"
            :on-error="handleUploadError"
            :show-file-list="false" style="display:inline-block;margin:0 10px;">
          <el-button type="default" size="small">
            <d2-icon name="download" />
            导入
          </el-button>
          </el-upload>
      <!-- <el-button type="default" size="small" @click="handleFormSubmit">
        <d2-icon name="upload" />
        导出
      </el-button> -->
      <el-button type="default" size="small" @click="qy_fee_type">
        <d2-icon name="unlock" />
        启用
      </el-button>
      <el-button type="default" size="small" @click="qy_fee_type">
        <d2-icon name="unlock-alt" />
        停用
      </el-button>
      <el-button
        type="default"
        size="small"
        @click="handle_refreshCurrent"
      >
        <d2-icon name="refresh" />
        刷新
      </el-button>
    </div>
    <el-card shadow="never" class="d2-mb">
      <el-table
        :data="FeeTypetableData"
        border :header-cell-style="{ background: '#eef1f6' }"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40"> </el-table-column>
        <el-table-column type="index" label="序号" width="55"></el-table-column>
        <el-table-column prop="status" label="状态" sortable :formatter="formatterStatus"></el-table-column>
        <el-table-column prop="name" label="名称" sortable></el-table-column>
        <el-table-column prop="currency_name" label="币种" sortable disabled></el-table-column>
        <!-- <el-table-column prop="currency" label="币种ID" sortable disabled></el-table-column> -->
        <el-table-column prop="price" label="默认单价" sortable></el-table-column>
        <el-table-column prop="rate" label="税率" sortable></el-table-column>
        <el-table-column prop="desc" label="备注" sortable></el-table-column>
      </el-table>
    </el-card>
    <!-- 新增 -->
    <el-dialog :visible.sync="add_feeTypeVisible" title="费用信息-新增">
       <div>
    <div class="mb">
      <el-button type="default" size="small" @click="addRow">
        <d2-icon name="plus"/>
        增行
      </el-button>
      <el-button type="default" size="small" icon="el-icon-delete" @click="delData">
        删行
      </el-button>
    </div>
     <el-form label-position="right" status-icon :rules="rules" :model="add_feeTypetableData" ref="ruleForm">
    <el-table :data="add_feeTypetableData" border :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow'>
        <el-table-column type="selection" width="40" align="center"></el-table-column>
      <el-table-column type="index" :index="indexMethod" label="序号" width="55">
      </el-table-column>
      <el-table-column label="状态" width="100" sortable>
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.status'" :rules="rules.status">
          <el-select  clearable v-model="scope.row.status" placeholder="请选择" filterable allow-create>
			         <el-option label="停用" value="0"></el-option>
               <el-option label="启用" value="1"></el-option>
			     </el-select>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="150">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.name'" :rules="rules.name">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.name"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="币种" width="130">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.currency'" :rules="rules.currency">
         <el-select
                v-model="scope.row.currency"
                placeholder="请选择"
                style="width:100%;"
              >
               <el-option
                         v-for="item in selectCurrencyList"
                         :key="item.currency"
                         :label="item.name"
                         :value="item.currency"
                 >
                     <span style="float: left">{{item.name}}</span>
                     <!-- <span style="float: right; color: #8492a6; font-size: 13px">{{ item.currency}}</span> -->
                 </el-option>
              </el-select>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="默认单价" width="110">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.price'" :rules="rules.price">
          <el-input
          type="number"
            placeholder="请输入内容"
            v-model="scope.row.price"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税率" width="110">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.rate'" :rules="rules.rate">
          <el-input
          type="number"
            placeholder="请输入内容"
            v-model="scope.row.rate"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="备注">
        <template slot-scope="scope">
            <el-form-item :prop="scope.$index + '.desc'" :rules="rules.desc">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.desc"
          ></el-input>
            </el-form-item>
        </template>
      </el-table-column>
    </el-table>
     </el-form>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="add_feeTypeVisible = false">取消</el-button>
        <el-button type="primary" @click="add_feeTypeChange('ruleForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
     <!-- 修改 -->
    <el-dialog :visible.sync="edit_feeTypeVisible" title="费用信息-修改">
       <div>
          <el-form label-position="right" status-icon :rules="rules" :model="edit_feeTypetableData" ref="ruleForm">
    <el-table :data="edit_feeTypetableData" border>
      <el-table-column type="index" :index="indexMethod" label="序号" width="55">
      </el-table-column>
       <el-table-column label="状态" width="100" sortable>
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.status'" :rules="rules.status">
          <el-select  clearable v-model="scope.row.status" placeholder="请选择" filterable allow-create>
			         <el-option label="停用" value="0"></el-option>
               <el-option label="启用" value="1"></el-option>
			     </el-select>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="150">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.name'" :rules="rules.name">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.name"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="币种" width="130">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.currency'" :rules="rules.currency">
         <el-select
                v-model="scope.row.currency"
                placeholder="请选择"
                style="width:100%;"
              >
               <el-option
                         v-for="item in selectCurrencyList"
                         :key="item.currency"
                         :label="item.name"
                         :value="item.currency"
                 >
                     <span style="float: left">{{item.name}}</span>
                     <!-- <span style="float: right; color: #8492a6; font-size: 13px">{{ item.currency}}</span> -->
                 </el-option>
              </el-select>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="默认单价" width="110">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.price'" :rules="rules.price">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.price"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税率" width="110">
        <template slot-scope="scope">
           <el-form-item :prop="scope.$index + '.rate'" :rules="rules.rate">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.rate"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="备注">
        <template slot-scope="scope">
            <el-form-item :prop="scope.$index + '.desc'" :rules="rules.desc">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.desc"
          ></el-input>
            </el-form-item>
        </template>
      </el-table-column>
    </el-table>
          </el-form>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="edit_feeTypeVisible = false">取消</el-button>
        <el-button type="primary" @click="edit_feeTypeChange('ruleForm')">保存</el-button
        >
      </span>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog :visible.sync="drfeeTypeVisible" title="导入费用信息">
       <div>
    <el-table :data="drfeeTypetableData" border :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow'>
      <el-table-column type="index" label="序号">
      </el-table-column>
      <el-table-column prop="status" label="状态" sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" sortable>
      </el-table-column>
      <el-table-column prop="currency" label="币种ID" sortable>
      </el-table-column>
      <el-table-column prop="price" label="默认单价" sortable>
      </el-table-column>
      <el-table-column prop="rate" label="税率" sortable>
      </el-table-column>
      <el-table-column prop="desc" label="备注" sortable>
      </el-table-column>
    </el-table>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="drfeeTypeVisible = false">取消</el-button>
        <el-button type="primary" @click="drfeeType"
          >上传数据</el-button
        >
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import DemoPageFooter from "../../../components/PageFooter";
import { conFeetype, addFeetype, conCurrency } from '../../../api/url_lcc';
export default {
  //费用信息
  name: "type_of_expense",
  components: {
    "demo-page-footer": DemoPageFooter,
  },
  data() {
    return {
       // 导入
      uploadUrl:`/user/lead/`,
      drfeeTypeVisible:false,
      drfeeTypetableData:[],
      selectCurrencyList:[],
      FeeTypetableData:[],
      add_feeTypeVisible: false,
      edit_feeTypeVisible: false,
      FYForm: {},
      add_feeTypetableData:[{
        status:"",
        name:"",
        currency:"",
        price:""||0,
        rate:""||0,
        desc:""
      }
        

      ],
      edit_feeTypetableData:[],
      row: "",
      rowNum: 1,
      page: {
        pageCurrent: 1,
        pageSize: 10,
        pageTotal: 0
      },
       ruleForm:{
        "status":"",
        "name":"",
        "currency":"",
        "price":0,
        "rate":0,
        "desc":""
      },
      rules:{
        status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
        name: [
         { required: true, message: '请输入名称', trigger: 'blur' },
       ],
       currency: [
            { required: true, message: '请选择币种', trigger: 'change' }
          ],
      //  price: [
      //       { required: true, message: '请输入默认单价', trigger: 'blur' }
      //     ],
      //  desc: [
      //    { required: true, message: '请输入备注', trigger: 'blur' },
      //  ],
      //  rate: [
      //    { required: true, message: '请输入税率', trigger: 'blur' },
      //  ], 
      },
    };
  },
  created() {
           this.tabledatas.map(i => {
               i.show = false
               return i
           })
  },
  methods: {
    // 导入
      handleAvatarSuccess (res, file) {
        // this.uploadloading.close();
        console.log(444444,res.result);
        if (res && res.errcode === "1") {
           this.$message({
           message: '导入成功',
           type: 'success',
          })
          this.drfeeTypeVisible = true;
          this.drfeeTypetableData = [];
          var data1 = res.result.Sheet1;
          for (var i = 0; i < data1.length; i++) {
            this.drfeeTypetableData[i] = {
               status: data1[i].状态,
               name: data1[i].名称,
               currency: data1[i].币种ID,
               price: data1[i].默认单价,
               rate: data1[i].税率,
               desc: data1[i].备注
            }
          }
         
        } else {
          this.$message.error(res.msg);
        }
      },
      drfeeType(){
         var drfeeTypetableData = [];
        var drfeeTypetableData = this.drfeeTypetableData;
        drfeeTypetableData.forEach(function(item, index) {
           var data1 = item.status
          if (data1 == "停用") {
             item.status = '0';
         } else if (data1 == "启用") {
             item.status = '1';
         }
       })
        let params = { 
          "operation":"ADD",
          fee_type:this.drfeeTypetableData
        };
        addFeetype(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                this.drfeeTypeVisible = false;
                this.handlefee_typeChange();
           }).catch(err =>{
          this.$message.error(err.msg);
        });
      },
    // 可用状态
     formatterStatus(row,column){
        return row.status == 0?'停用':'启用'
    },
    // 币种
     formatterCurrency(row, column) {
         if (row.currency == "USD") {
             return '美元';
         } else if (row.currency == "CNY") {
             return '人民币';
         } else if (row.currency == "EUR") {
             return '欧元';
         } else if (row.currency == "GBP") {
             return '英镑';
         } 
     },
     // 查询币种
      handle_currencyChange(){
         let params = {
              "name": "",
          };
          conCurrency(params).then(res => {
              // if (res.errcode == "1") {
                 this.selectCurrencyList = []
                  var data1 = res.result
                  console.log(902,)
                for (var i = 0; i < data1.length; i++) {
                        this.selectCurrencyList[i] = {
                            currency: data1[i]['id'],
                            name: data1[i]['name']
                        };
                    }
              }).catch(err =>{
          this.$message.error(err.msg);
        });
      },
    // 查询
    handlefee_typeChange(){
       let params = {
            "name": this.FYForm.name || "",
            "status": this.FYForm.status || "",
            "currency": this.FYForm.id || "",
        };
        conFeetype(params).then(res => {
            // if (res.errcode == "1") {
                this.FeeTypetableData = []
                var data = res.result
                for (var i = 0; i < data.length; i++) {
                  this.FeeTypetableData[i] = {
                    currency: data[i]['currency'],
                    currency_name: data[i]['currency_name'],
                    desc: data[i]['desc'],
                    id: data[i]['id'],
                    name: data[i]['name'],
                    price: data[i]['price'],
                    rate: data[i]['rate'],
                    status: data[i]['status'].toString(),
                  }
              }
            }).catch(err =>{
          this.$message.error(err.msg);
        });
    },
    // 多选提示
    openMessage() {
      this.$message({
          dangerouslyUseHTMLString: true,
          type: 'error',
          message: '<strong>请勾选你要选择的行，再进行操作！</strong>'
      });
    },
     // 新增
    add_fee_type(){
        this.add_feeTypeVisible = true;
    },
    // 新增保存
    add_feeTypeChange(ruleForm){
      let params = {
           "operation":"ADD",
            "fee_type":this.add_feeTypetableData
        };
       const rule1 = new Promise((resolve, reject) => {
        this.$refs[ruleForm].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      Promise.all([rule1]).then(() => {
        addFeetype(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.add_feeTypeVisible = false
                 this.handlefee_typeChange()
            }).catch(err =>{
          this.$message.error(err.msg);
        });
         });
    },
    // 修改
    edit_fee_type(){
      if (this.multipleSelection == undefined) {
          this.openMessage();
      } else if(this.multipleSelection.length != 1){
         this.$message.error("修改只能选中一条数据进行！");
      } else {
         this.edit_feeTypeVisible = true
         this.edit_feeTypetableData = this.multipleSelection
      }
    },
    // 修改保存
    edit_feeTypeChange(ruleForm){
      let params = {
           "operation":"MOD",
            "fee_type":{
              "id":this.edit_feeTypetableData[0].id,
              "name": this.edit_feeTypetableData[0].name,
              "status": this.edit_feeTypetableData[0].status,
              "currency": this.edit_feeTypetableData[0].currency,
              "rate":this.edit_feeTypetableData[0].rate,
              "price":this.edit_feeTypetableData[0].price,
              "desc":this.edit_feeTypetableData[0].desc,
            }
        };
         const rule1 = new Promise((resolve, reject) => {
        this.$refs[ruleForm].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      Promise.all([rule1]).then(() => {
        addFeetype(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.edit_feeTypeVisible = false
                 this.handlefee_typeChange()
           }).catch(err =>{
          this.$message.error(err.msg);
        });
         });
    },
    // 删除
    del_fee_type(){
       this.$confirm('是否删除该费用信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           var data = this.multipleSelection
           var currList  = [];
           data.forEach(function(item, index) {
              var data1 = item.id
              currList.push(data1)
              console.log(90,data1,91,currList)
          })
          let params = {
           "operation":"DEL",
           "fee_type":currList
        };
        addFeetype(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                this.handlefee_typeChange();
            }).catch(err =>{
          this.$message.error(err.msg);
        });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
     
    },
    // 启用/ 停用
    qy_fee_type(){
       var data = this.multipleSelection
           var currList  = [];
           data.forEach(function(item, index) {
              var data1 = item.id
              currList.push(data1)
              console.log(90,data1,91,currList)
          })
      let params = {
           "operation":"STATUS",
            "fee_type":currList
        };
        addFeetype(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.handlefee_typeChange()
           }).catch(err =>{
          this.$message.error(err.msg);
        });
    },
    // 刷新
    handle_refreshCurrent(){
      this.FYForm.name = "",
      this.FYForm.status = "",
      this.FYForm.id = "",
      this.handlefee_typeChange()
    },
     // 行内编辑
    handleCellDataChange({ rowIndex, key, value, row }) {
      console.log(rowIndex);
      console.log(key);
      console.log(value);
      console.log(row);
    },
    // 多选
    handleSelectionChange(val) {
       this.multipleSelection = val;
       console.log('删除1',this.multipleSelection)
     },
      // 获取表格选中时的数据
      selectRow (val) {
        this.selectlistRow = val
      },
      // 增加行
      addRow () {
       	  var list = {
          rowNum:this.rowNum,
          status: "",	
          name: "",
          currency:"",    
          price:"",
          rate:"",
          desc:""
   		 };
        this.add_feeTypetableData.unshift(list)
        this.rowNum += 1;
      },
      // 删除方法
      // 删除选中行
      delData() {
        for (let i = 0; i < this.selectlistRow.length; i++) {
          let val = this.selectlistRow
          val.forEach((val, index) => {
            this.add_feeTypetableData.forEach((v, i) => {
              if (val.rowNum === v.rowNum) {
                // i 为选中的索引
                this.add_feeTypetableData.splice(i, 1)
              }
            })
          })
        }
        // 删除完数据之后清除勾选框
        this.$refs.table.clearSelection()
      },
    },
   mounted() {
      this.handlefee_typeChange();
      this.handle_currencyChange();
  }
  };
</script>
<style></style>
